<?php
/**
 * @author: yeran
 * @createTime: 2018-04-22 17:42
 * @description: 交易撤销接口
 */

namespace Payment;

use Payment\Cancel\FuCancel;
use Payment\Charge\LTF\LTFCancel;
use Payment\Charge\MiPay\MiCancel;
use Payment\Charge\Sw\SwCancel;
use Payment\Charge\SwThree\SwThreeCancel;
use Payment\Charge\TLpay\TLCancel;
use Payment\Charge\YS\YSCancel;
use Payment\Common\BaseStrategy;
use Payment\Common\PayException;

/**
 * Class CancelContext
 *
 * @package Payment
 */
class CancelContext{

	/**
	 * 退款的渠道
	 *
	 * @var BaseStrategy
	 */
	protected $cancelHandler;

	/**
	 * 设置对应的退款渠道
	 *
	 * @param string $channel 退款渠道
	 *  - @param array $config 配置文件
	 * @throws PayException
	 * @see Config
	 * @author yeran
	 */
	public function initCancelHandler($channel, array $config){
		try{
			switch($channel){
				case Config::TL_CHANNEL_LITE:
					$this->cancelHandler = new TLCancel($config);
					break;
				case Config::MI_CHANNEL_LITE:
					$this->cancelHandler = new MiCancel($config);
					break;
				case Config::SW_CHARGE:
					$this->cancelHandler = new SwCancel($config);
					break;
                case Config::SW_T_CHARGE:
                    $this->cancelHandler = new SwThreeCancel($config);
                    break;
				case Config::FU_CHARGE:
					$this->cancelHandler = new FuCancel($config);
					break;
				case Config::LTF_CHARGE:
					$this->cancelHandler = new LTFCancel($config);
					break;
                case Config::YS_CHARGE:
                    $this->cancelHandler = new YSCancel($config);
                    break;
				default:
					throw new PayException('当前仅支持：通联支付平台');
			}
		}catch(PayException $e){
			throw $e;
		}
	}

	/**
	 * 通过环境类调用交易撤销操作
	 *
	 * @param array $data
	 * @return array
	 * @throws PayException
	 * @author yeran
	 */
	public function cancel(array $data){
		if(!$this->cancelHandler instanceof BaseStrategy){
			throw new PayException('请检查初始化是否正确');
		}

		try{
			return $this->cancelHandler->handle($data);
		}catch(PayException $e){
			throw $e;
		}
	}
}
